﻿using CommonConfig;
using Newtonsoft.Json.Linq;
using SmartBusinessCardEntity;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using WXDataServer;
using WXEntity;

namespace WXServer
{
    class BaseServerImplement
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="requestEntity"></param>
        /// <param name="resultEntity"></param>
        /// <returns></returns>
        public string Register(RequestEntity requestEntity, ref ResultEntity resultEntity)
        {
            string msg = "";
            Dictionary<string, string> keyValuePairs = requestEntity.RequestParam as Dictionary<string, string>;
            string openid = keyValuePairs["openid"].ToString();
            string name = keyValuePairs["name"].ToString();
            string sex = keyValuePairs["sex"].ToString();
            string avatarurl = keyValuePairs["avatarurl"].ToString();
            DataRow dataRow;
            bool success = DataManager.Register(openid, name, sex, avatarurl,out msg,out dataRow);
            if (success)
            {
                resultEntity.Code = ErrorCode.RequestSuccess;
                UserInfo userInfo = new UserInfo();
                DwTool.BindProperty(userInfo,dataRow);
                resultEntity.ResultObject = GetAPIJson(requestEntity.ServiceCode, userInfo);
            }
            else
            {
                resultEntity.Code = ErrorCode.RequestFail;
                resultEntity.Msg = msg;
            }
            return msg;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="requestEntity"></param>
        /// <param name="resultEntity"></param>
        /// <returns></returns>
        public string Login(RequestEntity requestEntity, ref ResultEntity resultEntity)
        {
            string msg = "";
            Dictionary<string, string> keyValuePairs = requestEntity.RequestParam as Dictionary<string, string>;
            string code = keyValuePairs["code"].ToString();

            Dictionary<string, object> json = HttpTool.SendText("https://api.weixin.qq.com/sns/jscode2session",
                string.Format("appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", WXSetEntity.Instance.AppID, WXSetEntity.Instance.AppSecret, code));
            if (json.ContainsKey("session_key") && json.ContainsKey("openid"))
            {
                UserInfo userInfo = new UserInfo();
                userInfo.Openid = json["openid"].ToString();
                userInfo.SessionKey = json["session_key"].ToString();
                DataTable dataTable = DataManager.GetUserByOpenId(userInfo.Openid);
                if (dataTable.Rows.Count > 0)
                {
                    userInfo.IsRegister = true;
                    DwTool.BindProperty(userInfo, dataTable.Rows[0]);
                }       
                else
                {
                    userInfo.IsRegister = false;
                }

                resultEntity.Code = ErrorCode.RequestSuccess;
                resultEntity.ResultObject = GetAPIJson(requestEntity.ServiceCode, userInfo);
            }
            else
            {
                msg = "获取会话ID失败";
                resultEntity.Code = ErrorCode.RequestFail;
                resultEntity.Msg = msg;
            }
            return msg;
        }

        /// <summary>
        /// 根据接口配置信息返回接口json
        /// </summary>
        /// <param name="serviceCode"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        private object GetAPIJson(string serviceCode, object obj)
        {
            Type type = obj.GetType();
            PropertyInfo[] propertyInfos = type.GetProperties();
            string serviceCodePath = AppDomain.CurrentDomain.BaseDirectory + @"ApiDoc\" + serviceCode + ".config";
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(serviceCodePath);
            XmlNode outNode = xmlDocument.SelectSingleNode("/config/Out");
            if (outNode != null)
            {
                Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                XmlNodeList paramNodeList = outNode.ChildNodes;
                for (int i = 0; i < paramNodeList.Count; i++)
                {
                    XmlNode paramNode = paramNodeList[i];
                    if (paramNode.Attributes != null && paramNode.Attributes["name"] != null)
                    {
                        string paramName = paramNode.Attributes["name"].Value;
                        PropertyInfo propertyInfo = type.GetProperty(paramName);
                        if (propertyInfo != null)
                        {
                            object value = propertyInfo.GetValue(obj, null);
                            keyValuePairs.Add(paramName, value);
                        }
                    }
                }
                return keyValuePairs;
            }
            else
            {
                return obj;
            }
        }
    }
}
